package com.xinyin.aiqinhaiback.Utils;

import com.xinyin.aiqinhaiback.model.entity.Information;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class InformationTreeUtil {

	public synchronized static List<Map<String, Object>>  getData(List<Information> informations){

		List<Map<String, Object>> resList =new ArrayList<>();
		Map<String, Map<String, Object>> groupedData = informations.stream()
				.collect(Collectors.groupingBy(
						d -> d.getDeviceId() + "_" + d.getDeviceName(),  // 组合键避免重复设备
						Collectors.collectingAndThen(
								Collectors.toList(),
								list -> {
									Information first = list.get(0);
									Map<String, Object> firstLevel = new HashMap<>();
									firstLevel.put("deviceId", first.getDeviceId());
									firstLevel.put("deviceName", first.getDeviceName());
									firstLevel.put("description", first.getDescription());
									// 按 classify 分组（第二级）
									Map<String, Map<String, Object>> secondLevel = list.stream()
											.collect(Collectors.groupingBy(
													d -> d.getClassify(),
													Collectors.collectingAndThen(
															Collectors.toList(),
															subList -> {
																Information subFirst = subList.get(0);
																Map<String, Object> classifyMap = new HashMap<>();
																classifyMap.put("classify", subFirst.getClassify());

																// 按 informationName 分组（第三级）
																List<Map<String, Object>> thirdLevel = subList.stream()
																		.map(item -> {
																			Map<String, Object> infoMap = new HashMap<>();
																			infoMap.put("informationName", item.getInformationName());
																			infoMap.put("value", item.getValue()!=null?item.getValue():null);
																			infoMap.put("unit", item.getUnit());
																			infoMap.put("id", item.getId());
																			infoMap.put("modbus", item.getModbus());
																			infoMap.put("address", item.getAddress());
																			return infoMap;
																		}).collect(Collectors.toList());

																classifyMap.put("dataList", thirdLevel);
																return classifyMap;
															}
													)
											));
									firstLevel.put("dataList", new ArrayList<>(secondLevel.values()));
									resList.add(firstLevel);
									return firstLevel;
								}
						)
				));
		return resList;
	}
}
